package com.mobi.Survey.map;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.mobi.Survey.adapters.CustomAdapterCategoriesAddBusiness;
import com.mobi.Survey.lib.activities.AbstractScreen;
import com.mobi.Survey.lib.utils.Helper;

public class SelectCategoryScreen extends AbstractScreen {
	private CustomAdapterCategoriesAddBusiness adapter;
	private ListView lvSelectCategoreis;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		String selectedCat = getIntent().getExtras().getString("selected_categories");
		if (selectedCat.length() > 0) {
			String cats[] = selectedCat.split(",");
			for (String cat : cats) {
				long catid = Helper.toLong(cat);
				if(catid!=0)
				adapter.getSelectedCategories().add(catid);
			}

		}

		setTitle(getResources().getString(R.string.select_three_cat));
		getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
		lvSelectCategoreis.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> av, View v, int position, long id) {
				if (!adapter.isSubCategoryView()) {
					adapter.switchToSubCategoryView(true);
					adapter.setData(MapHelper.categories.get(position).getSubCategories());
					setTitle(MapHelper.categories.get(position).getName());

					adapter.notifyDataSetChanged();
				}

			}
		});
	}

	@Override
	protected void initUiVars() {
		lvSelectCategoreis = (ListView) findViewById(R.id.lvSelectCategoreis);
		adapter = new CustomAdapterCategoriesAddBusiness(this, MapHelper.categories);
		lvSelectCategoreis.setAdapter(adapter);

	}

	@Override
	protected int getLayoutId() {

		return R.layout.select_categories;
	}

	public void onClick(View v) {
		if (v.getId() == R.id.btnAdd) {
			Intent returnIntent = new Intent();
			returnIntent.putExtra("result", adapter.getSelectedCategories().toString());
			setResult(RESULT_OK, returnIntent);
			finish();
		} else if (v.getId() == R.id.btnClearSelectedCats) {
			adapter.getSelectedCategories().clear();
			adapter.notifyDataSetChanged();
			Toast.makeText(this, "Categories Cleard", Toast.LENGTH_LONG).show();
		}
	}

	@Override
	protected void onRelease() {

	}

	@Override
	public void onBackPressed() {

		if (adapter.isSubCategoryView()) {
			adapter.switchToSubCategoryView(false);
			adapter.setData(MapHelper.categories);
			adapter.notifyDataSetChanged();
			setTitle(getResources().getString(R.string.select_three_cat));

		} else {
			finish();
		}

	}

}
